#!/bin/bash

# CMDB资产管理系统启动脚本

echo "=========================================="
echo "CMDB资产管理系统 - 启动脚本xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
echo "=========================================="
echo ""

# 检查是否在正确的目录
if [ ! -d "backend" ] || [ ! -d "frontend" ]; then
    echo "错误: 请在项目根目录运行此脚本"
    exit 1
fi

# 启动后端
echo "启动后端服务..."
cd backend

# 检查虚拟环境
if [ ! -d "venv" ]; then
    echo "创建Python虚拟环境..."
    python3 -m venv venv
fi

# 激活虚拟环境
source venv/bin/activate

# 安装依赖
echo "安装后端依赖..."
pip install -q -r requirements.txt

# 数据库迁移
if [ ! -f "db.sqlite3" ]; then
    echo "初始化数据库..."
    python manage.py makemigrations
    python manage.py migrate
    
    echo ""
    echo "创建管理员账户（可选，按Ctrl+C跳过）："
    python manage.py createsuperuser || true
fi

# 启动后端服务
echo ""
echo "启动后端服务（端口8000）..."
python manage.py runserver 0.0.0.0:8000 &
BACKEND_PID=$!

cd ..

# 启动前端
echo ""
echo "启动前端服务..."
cd frontend

# 检查node_modules
if [ ! -d "node_modules" ]; then
    echo "安装前端依赖（可能需要几分钟）..."
    npm install
fi

# 启动前端服务
echo ""
echo "启动前端服务（端口8080）..."
npm run dev &
FRONTEND_PID=$!

cd ..

echo ""
echo "=========================================="
echo "✓ 服务启动完成！"
echo "=========================================="
echo ""
echo "后端地址: http://localhost:8000"
echo "前端地址: http://localhost:8080"
echo "后端管理: http://localhost:8000/admin"
echo ""
echo "按 Ctrl+C 停止所有服务"
echo "=========================================="

# 等待用户中断
wait
